package com.daily.videoedit.app;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.multidex.MultiDexApplication;

import com.daily.videoedit.R;
import com.daily.videoedit.activity.SplashActivity;
import com.daily.videoedit.constants.Config;
import com.daily.videoedit.dao.DaoSharedPreferences;
import com.daily.videoedit.model.ChannelInfo;
import com.daily.videoedit.model.User;
import com.daily.videoedit.utils.SystemUtil;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.xunxi.mimi.utils.CrashHandler;
import com.xunxi.mimi.utils.LogUtil;
import com.xunxi.mimi.utils.SDCardUtil;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

/**
 * 作者: liyu on  2017/11/15 0015 13:58
 * 邮箱：liyu@szy.cn
 * 功能描述:
 * 备注:
 */
public class App extends MultiDexApplication implements CrashHandler.UncaughtExceptionHanlderListener {

    private static App mInstance;
    private User mUserInfo;
    private String mToken;

    //设备信息
    private String deviceInfo;
    //设备id
    private String deviceId = null;

    public static App getInstance() {
        synchronized (App.class) {
            if (mInstance == null) {
                mInstance = new App();
            }
        }
        return mInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mInstance = this;
        initLog();//日志
        initSmartRefresh();
    }

    private void initLog() {
        LogUtil.init(Config.PRINT_LOG);
        CrashHandler.getInstance(this).setHanlderListener(this);
        CrashHandler.getInstance(this).setCrashLogDir(getCrashLogDir());//设置记录错误日志目录
    }

    private void initSmartRefresh() {
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                ClassicsFooter footView = new ClassicsFooter(App.this);
                footView.setTextSizeTitle(14);
                footView.setAccentColorId(R.color.color_999999);
                return footView;
            }
        });
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                MaterialHeader materialHeader = new MaterialHeader(App.this);
                materialHeader.setColorSchemeColors(getResources().getColor(R.color.color_fd5253));
                return materialHeader;
            }
        });
    }

    public User getUserInfo() {
        if (mUserInfo == null) {
            mUserInfo = DaoSharedPreferences.getInstance().getUserInfo();
        }
        return mUserInfo;
    }

    public void setUserInfo(User userInfo) {
        this.mUserInfo = userInfo;
        DaoSharedPreferences.getInstance().setUserInfo(mUserInfo);
    }

    public void setToken(String token) {
        mToken = token;
        DaoSharedPreferences.getInstance().setToken(token);
    }

    public String getToken() {
        if (TextUtils.isEmpty(mToken)) {
            mToken = DaoSharedPreferences.getInstance().getToken();
        }
        return mToken;
    }

    public void exitLogin() {
        mUserInfo = null;
        DaoSharedPreferences.getInstance().clearUserInfo();
        removeJPush();
    }

    private void removeJPush() {
        Set<String> set = new HashSet<String>();
        set.add("all"); // 这指定all 是给所有人发信息 set是TAG
//        JPushInterface.setAliasAndTags(this, "", set, null);
//        JPushInterface.clearAllNotifications(this);
    }


    public void exit() {
    }

    // 获取设备ID
    public String getDeviceId() {
        if (TextUtils.isEmpty(deviceId)) {
            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            if (tm != null) {
                deviceId = tm.getDeviceId();
            }
            if (TextUtils.isEmpty(deviceId)) {
                deviceId = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);
            }
        }
        return deviceId;
    }

    protected String getCrashLogDir() {
        StringBuffer sb = new StringBuffer();

        if (getRootDir() != null) {
            sb.append(getRootDir());
            sb.append(File.separator);
        } else {
            sb.append(File.separator);
            sb.append("sdcard");
            sb.append(getPackageName());
            sb.append(File.separator);
        }

        sb.append("log");

        return sb.toString();
    }

    protected String getRootDir() {
        if (SDCardUtil.isSDCardAvaiable()) {
            StringBuffer sb = new StringBuffer();
            sb.append(Environment.getExternalStorageDirectory().getPath());
            sb.append(File.separator);
            sb.append(getPackageName());

            return sb.toString();
        }

        return null;
    }

    public String getDeviceInfo() {
        if (TextUtils.isEmpty(deviceInfo)) {
            deviceInfo = SystemUtil.getDeviceBrand() + "|" + SystemUtil.getSystemModel() + "|" + SystemUtil.getSystemVersion();
        }
        return deviceInfo;
    }

    @Override
    public void handlerUncaughtException(Thread thread, Throwable ex) {
        if (!Config.DEBUG) {
            AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(this, SplashActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent restartIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
            mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 500, restartIntent); // 0.5秒钟后重启应用
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }
}
